"use strict";

const Controller = require("egg").Controller;

const dayjs = require("dayjs");

class ArticleController extends Controller {
  async index() {
    const { ctx, app } = this;

    const {
      current,
      size,
      url = "",
      ip = "",
      brower = "",
      core = "",
      os = "",
      device = "",
      area = "",
    } = ctx.request.body;

    let sql = " ";

    if (url) {
      sql += `where url = "${url}" `;
    } else if (ip) {
      sql += `where ip = "${ip}" `;
    } else if (brower) {
      sql += `where brower = "${brower}" `;
    } else if (core) {
      sql += `where core = "${core}" `;
    } else if (os) {
      sql += `where os = "${os}" `;
    } else if (device) {
      sql += `where device = "${device}" `;
    } else if (area) {
      sql += `where area = "${area}" `;
    }

    let limit = ` limit ${(current - 1) * size} , ${size}`;

    const data = await app.mysql.query(`select * from visit ` + sql + limit);

    const total = (
      await app.mysql.query(`select count(*) as count from visit` + sql)
    )[0].count;

    ctx.body = {
      code: 1,
      data,
      total,
    };
  }

  async add() {
    const { ctx, app } = this;

    let { url, ip, area, brower, os } = ctx.request.body;

    url = "http://10.6.8.84:8080" + url;

    await app.mysql.insert("visit", {
      url,
      ip,
      brower,
      area,
      os,
      createtime: dayjs(new Date().getTime()).format("YYYY-MM-DD HH:mm:ss"),
    });

    ctx.body = {
      code: 1,
      msg: "添加成功",
    };
  }

  async del() {
    const { ctx, app } = this;

    const { id } = ctx.request.body;

    const multipleSelection = ctx.request.body;

    if (id) {
      await app.mysql.delete("file", { id });
    }

    if (multipleSelection.length) {
      multipleSelection.forEach(async (item) => {
        await app.mysql.delete("file", { id: item.id });
      });
    }

    ctx.body = {
      code: 1,
      msg: "删除成功",
    };
  }
}

module.exports = ArticleController;
